<template>
  <div>
    <el-dialog
      v-model="isShowDialog"
      :title="`${props.type}跟进记录`"
      width="50%"
      align-center
      @close="closeShareDialog"
      @opened="loadContent"
    >
      <el-divider style="margin-top: 0" />
      <div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="跟进方式" prop="state">
            <el-select
              v-model="ruleForm.state"
              placeholder="请选择跟进方式"
              style="width: 60%"
              clearable
            >
              <el-option
                v-for="item in followMethodsList.value"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
                :disabled="item.dictValue == '5'"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="跟进阶段" prop="phase">
            <el-select
              v-model="ruleForm.phase"
              placeholder="请选择跟进阶段"
              style="width: 60%"
              clearable
            >
              <el-option
                v-for="item in followPhaseList.value"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
                :disabled="item.dictValue == '10'"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="跟进时间">
            <el-date-picker
              v-model="contactTime"
              type="date"
              placeholder="请选择跟进时间"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              :disabled="true"
            />
            <!-- <el-date-picker
              v-model="ruleForm.contactTime"
              type="datetime"
              placeholder="请选择跟进时间"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            /> -->
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShowDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmClick"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getFollowMethods,
  getFollowPhase,
  followSave,
} from "@/api/studentManagement/index.js";
import { ElMessageBox, ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const props = defineProps({
  isShowDialog: {
    type: Boolean,
    default: false,
  },
  studentRow: {
    type: Object,
  },
  type: {
    type: String,
  },
});

// 控制开关
const emit = defineEmits(["update:isShowDialog", "update:tableList"]);
const isShowDialog = ref(props.isShowDialog);
watch(
  () => props.isShowDialog,
  (newValue) => {
    isShowDialog.value = newValue;
  }
);
const closeShareDialog = () => {
  resetForm();
  isShowDialog.value = false;
  emit("update:isShowDialog", false);
};
function cancelClick() {
  closeShareDialog();
}
//获取跟进阶段下拉列表
const followPhase = ref("");
const followPhaseList = reactive([]);
const toGetFollowPhase = async () => {
  try {
    const res = await getFollowPhase({});
    if (res.code === 200) {
      followPhaseList.value = res.data;
      // followPhaseList.value = followPhaseList.value.filter(item => item.dictLabel !== "更新跟进人");
    }
  } catch (error) {
    console.error("获取跟进阶段下拉列表失败:", error);
  }
};
onMounted(toGetFollowPhase);
//获取跟进方式下拉列表
const followMethods = ref("");
const followMethodsList = reactive([]);
const toGetFollowMethods = async () => {
  try {
    const res = await getFollowMethods({});
    if (res.code == 200) {
      followMethodsList.value = res.data;
      // followMethodsList.value = followMethodsList.value.filter(item => item.dictLabel !== "其他");
    }
  } catch (error) {
    console.error("获取任务状态下拉列表失败:", error);
  }
};
onMounted(toGetFollowMethods);
//表单部分
const formatDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
const ruleFormRef = ref(null);
const fTime = ref(null);
const nextFTime = ref(null);
const contactTime = ref(formatDate());
const ruleForm = ref({});
const loadContent = () => {
  console.log("组件打开", props.type);
  if (props.type === "添加") {
    ruleForm.value = { studentId: props.studentRow.studentId, type: 1 };
    console.log(ruleForm.value);
  } else if (props.type === "修改") {
    ruleForm.value = { ...props.studentRow, type: 2 };
  }
};
//表单校验
const rules = reactive({
  state: [
    {
      required: true,
      message: "请选择跟进方式",
      trigger: "change",
    },
  ],
  phase: [
    {
      required: true,
      message: "请选择跟进阶段",
      trigger: "change",
    },
  ],
  // contactTime: [
  //   {
  //     type: "date",
  //     required: true,
  //     message: "请选择跟进时间",
  //     trigger: "change",
  //   },
  // ],
});
//提交表单
function confirmClick() {
  console.log("ruleForm", ruleForm.value);
  ElMessageBox.confirm(`确定跟进吗?`)
    .then(() => {
      proxy.$refs["ruleFormRef"].validate(async (valid) => {
        if (valid) {
          // ruleForm.value.contactTime = formatDate(
          //   new Date(ruleForm.value.contactTime)
          // )
          try {
            const res = await followSave({
              ...ruleForm.value,
              contactTime: contactTime.value,
            });
            if (res.code == 200) {
              closeShareDialog();
              proxy.$modal.msgSuccess("学员跟进成功");
              emit("update:tableList");
            }
          } catch (error) {
            console.error("跟进失败:", error);
          }
        } else {
          proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
        }
      });
    })
    .catch(() => {
      // catch error
    });
}
//重置表单
const resetForm = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
};
</script>

<style lang="scss" scoped></style>
